package com.lei.util;

import javax.servlet.Filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Lei Chu
 * @Date 2020/10/24 12:54
 */

@WebFilter(filterName = "SessionFilter",value = "/*")
public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig config) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //取到你访问的资源
        String uri = request.getRequestURI();

        //静态资源默认访问路径在/下，所以放过
        if ("/index.jsp".equals(uri)|| "/staffServlet/checkLogin".equals(uri)||isStaticResource(uri)||uri.contains("/static")){
            //过滤链放行
            chain.doFilter(req, resp);
        }else {
            if (request.getSession().getAttribute("nowStaff") == null) {
                response.sendRedirect("/index.jsp");
            } else {
                //过滤链放行
                chain.doFilter(req, resp);
            }
        }

    }

    private Set<String> staticResourceTypes = new HashSet<String>();{
        staticResourceTypes.add(".css");
        staticResourceTypes.add(".js");
        staticResourceTypes.add(".png");
        staticResourceTypes.add(".jpg");
        staticResourceTypes.add(".otf");
        staticResourceTypes.add(".eot");
        staticResourceTypes.add(".svg");
        staticResourceTypes.add(".ttf");
        staticResourceTypes.add(".woff");
        staticResourceTypes.add(".gif");
        staticResourceTypes.add(".ico");
        staticResourceTypes.add(".txt");
        staticResourceTypes.add(".gzip");
        staticResourceTypes.add(".xz");
        staticResourceTypes.add(".tar.gz");
        staticResourceTypes.add(".tar.bz2");
        staticResourceTypes.add(".jar");
        staticResourceTypes.add(".war");
        staticResourceTypes.add(".7z");
        staticResourceTypes.add(".tgz");
        staticResourceTypes.add(".gz");
        staticResourceTypes.add(".map");
    }

    public final boolean isStaticResource(String url) {

        boolean result = false;
        if (url==""||url==null) {
            return result;
        }
        int start = url.lastIndexOf(".");
        if (start < 0) {
            return result;
        }
        String prex = url.substring(start, url.length());
        return staticResourceTypes.contains(prex);
    }
}
